<script setup lang="ts">

import {message} from "ant-design-vue";
import md5 from "md5";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import ChartComponent from "~/contentScripts/views/sycm/flow_monitor_overview/components/ChartComponent.vue";
import TableComponent from "~/contentScripts/views/sycm/flow_monitor_overview/components/TableComponent.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {RiseOutlined, FallOutlined} from "@ant-design/icons-vue";
import {isLogin, userInfo} from "~/logic";
import {getCurrentInstance} from "vue";
import SYCM, {SYCMCache} from "~/utils/ali/sycm";
import {
  getFlowMonitorOverviewInterception, getFlowMonitorTrendInterception
} from "~/utils/interception/sycm/flowMonitorOverviewInterception";
import RequestInterception from "~/utils/RequestInterception";

const {proxy} = getCurrentInstance();
const req: RequestInterception = proxy.$req;
const visible = ref(false);
const loginVisible = ref(false);
onMounted(() => {
  userInfo()
})
const overviewData = ref<any>([]);
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    }
  }, __option)) {
    loadData();
  }
}
const tabActiveKey = ref(0);
const childTabs = ref<Array<any>>([]);
const typeName = ref('所有终端');
const tabs = ref<any>([]);
const loadData = async () => {
  typeName.value = await SYCM.getInternalFiberData("#flow-overview-floor-summary div.oui-card-header-wrapper > div.oui-card-header > div.oui-card-header-item.oui-card-header-item-pull-right > div.oui-select.oui-select-no-border.overview-summary-device-select.ant-select.ant-select-enabled > div > div > div", 'memoizedProps.children');
  // let data = req.getResponse(getFlowMonitorOverviewInterception);
  // if (!data) {
  //   message.error('获取数据失败，请刷新页面后重试！');
  //   return;
  // }
  // overviewData.value = data.data;
  tabs.value = await SYCM.flowMonitorOverviewTabs();
  tabs.value.map((item: any) => {
    if (item.active) {
      tabActiveKey.value = item.key;
    }
  })
  await loadChildTabs();
  visible.value = true;
}
const loadingChildTabs = ref(false);
const childTabActiveKey = ref('');
const loadChildTabs = async () => {
  loadingChildTabs.value = true;
  childTabs.value = [];
  document.querySelectorAll(`#flow-overview-floor-summary  div.alife-one-design-sycm-indexes-trend-index-item-selectable`)[tabActiveKey.value].click();
  let data = null;
  while (data == null) {
    data = await SYCM.flowMonitorOverviewChildTabs();
    // console.log(data);
  }
  loadingChildTabs.value = false;
  // 遍历子tab获取active
  data.map((item: any) => {
    if (item.active) {
      childTabActiveKey.value = item.key;
    }
  })
  childTabs.value = data;
}

const changeChildTab = async (item: any) => {
  childTabActiveKey.value = item.key;
  let oldData = await SYCM.getFlowMonitorOverviewChildTabsChartData();
  document.querySelector(`#sycm-flow-overview-board-summary-indexes-trend > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content > div > div.alife-one-design-sycm-indexes-trend-index-container div.alife-one-design-sycm-indexes-trend-index-item-multiple-line-selectable.alife-one-design-sycm-indexes-trend-index-item-${item.key}`).click();
  let data = await SYCM.getFlowMonitorOverviewChildTabsChartData();
  while (data == null || typeof data.data == 'undefined' || JSON.stringify(data) == JSON.stringify(oldData)) {
    data = await SYCM.getFlowMonitorOverviewChildTabsChartData();
  }
  await SYCMCache.set(md5(`FlowMonitorOverviewChildTabsChartData_${item.key}${item.numberValue}${JSON.stringify(item.subIndexes)}`), data, 60 * 60 * 24);
  childTabs.value.map((item: any) => {
    if (item.key == childTabActiveKey.value) {
      item.active = true;
      item.data = data;
    } else {
      item.active = false;
    }
  })
}
</script>

<template>
  <base-app>
    <a-button-group>
      <user @login="loginVisible=true" :style="{
        marginRight: '0',
      }"
      />
      <a-button type="primary" @click="handle" size="small">一键转化</a-button>
    </a-button-group>
    <a-modal :footer="false" v-model:visible="visible" width="95%" style="top: 20px;"
             :title="`流量看板-流量总览-${typeName}`"
    >
      <a-tabs style="height: calc(100vh - 120px);overflow-y: auto;" v-model:active-key="tabActiveKey" @change="loadChildTabs">
        <a-tab-pane v-for="(item,index) in tabs" :tab="item.props.text" :key="index">
          <a-spin style="min-height: 204px;" :spinning="loadingChildTabs">
            <a-row :gutter="10" class="child-tab">
              <a-col :span="4" v-for="(tab,k) in childTabs">
                <div class="child-tab-item" :class="{
                  active: childTabActiveKey==tab.key,
                  dashed: tab.data==null,
                }" @click="()=>changeChildTab(tab)"
                >
                  <h4>{{ tab.name }}</h4>
                  <h2 v-if="tab.format=='.2%'">{{ tab.numberValue.toFixed(2) }}%</h2>
                  <h2 v-else-if="tab.format.indexOf('.2f')">{{ tab.numberValue.toFixed(2) }}</h2>
                  <h2 v-else>{{ tab.numberValue }}</h2>
                  <a-row type="flex" class="bottom">
                    <a-col flex="1">
                      {{ tab.subIndexes[0].text }}
                    </a-col>
                    <a-col>
                      <template v-if="tab.subIndexes[0].numberValue">
                        <div v-if="tab.subIndexes[0].numberValue>0" class="blue">
                          +{{ (tab.subIndexes[0].numberValue * 100).toFixed(2) }}%
                          <RiseOutlined/>
                        </div>
                        <div v-else-if="tab.subIndexes[0].numberValue<0" class="red">
                          {{ (tab.subIndexes[0].numberValue * 100).toFixed(2) }}%
                          <FallOutlined/>
                        </div>
                      </template>
                      <template v-else>
                        --
                      </template>
                    </a-col>
                  </a-row>
                </div>

              </a-col>
            </a-row>
          </a-spin>
          <!--          // 统计图-->
          <ChartComponent :active-tab="childTabs.length>0?childTabs.find(item => item.active):null"/>
          <a-divider/>
<!--          [${tabs.length>0?tabs.find(item => item.active).props.text:''}]-->
          <table-component :tableName="`流量看板-流量总览-${typeName}`" :child-tabs="childTabs"/>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
    <user-login-modal v-model:visible="loginVisible" @close="loginVisible=false"/>
  </base-app>
</template>

<style lang="less" scoped>
.child-tab-item {
  border: 2px solid #eee;
  padding: 7px 14px;
  border-radius: 5px;
  margin-bottom: 10px;
  cursor: pointer;

  &.dashed {
    border-style: dashed;
  }

  &:hover, &.active {
    border-color: #1890ff;
  }

  .bottom {
    color: #666;
    font-size: 12px;

    .blue {
      color: #1890ff;
    }

    .red {
      color: #f5222d;
    }
  }
}
</style>
